const express = require('express');
let router = express.Router();
const path = require('path');
const formidable = require('formidable');
const { login, adddUser } = require('./login');
const { getType, delType, adddType } = require('./type');
const {
  adddAnimal,
  getAnimalList,
  delAnimal,
  getListByType,
  getAnimalById,
} = require('./animal');

router.post('/login', login);
router.post('/adddUser', adddUser);
router.get('/getType', getType);
router.post('/delType', delType);
router.post('/adddType', adddType);
router.get('/getAnimalList', getAnimalList);
router.post('/adddAnimal', adddAnimal);
router.post('/delAnimal', delAnimal);
router.post('/getListByType', getListByType);
router.post('/getAnimalById', getAnimalById);

//上传文件
router.post('/upload', (req, res) => {
  const form = formidable({
    multiples: true,
    uploadDir: path.join(path.dirname(__dirname), 'uploads'),
    keepExtensions: true,
  });
  form.parse(req, (err, fields, files) => {
    let imageReg = files.file.mimetype.indexOf('image/') == -1;
    let videoReg = files.file.mimetype.indexOf('video/') == -1;

    if (err) {
      res.send({ code: 500, msg: '服务器错误' });
    } else if (imageReg && videoReg) {
      res.send({ code: 250, msg: '请上传图片或者视频哦' });
    } else {
      let img = path.basename(files.file.newFilename);
      res.send({
        code: 1,
        msg: `${imageReg ? '视频' : '图片'}上传成功`,
        data: '/uploads/' + img,
      });
    }
  });
});

module.exports = router;
